<?php

define ('kWebMethod', 'kWebMethod');
define ('kWebPath', 'kWebPath');
define ('kWebPathPattern', 'kWebPathPattern');
define ('kWebGET', 'kWebGET');
define ('kWebPOST', 'kWebPOST');
define ('kWebCookies', 'kWebCookies');
define ('kWebValidate', 'kWebValidate');
define ('kWebHeaders', 'kWebHeaders');
define ('kWebQueryString', 'kWebQueryString');

function WebSignatureFromString($str) {
	static $regexp = '/^([a-zA-Z]+)(\\[(.*)\\])?\\s+(.*?)(\\?(.*))?$/';
	static $method = 1; static $listOfMethodCaptures = 3; static $pattern = 4;
	static $queryString = 6;
	
	if (!preg_match($regexp, $str, $matches)) return null;
	
	$list = array();
	if (trim($matches[$listOfMethodCaptures])) {
		$rawList = explode(',', $matches[$listOfMethodCaptures]);
	
		foreach ($rawList as $item)
			$list[] = ltrim(trim($item), '$');
	}
	
	$whatMethod = ($matches[$method] == 'POST')? kWebPOST : kWebGET;
	$result = array(
		kWebMethod => $matches[$method],
		$whatMethod => $list,
		kWebPathPattern => $matches[$pattern],
	);
	
	if (@$matches[$queryString])
		$result[kWebQueryString] = $matches[$queryString];
		
	return $result;
}

function WebSignatureFromValue($v) {
	if (is_array($v)) return $v;
	if (is_object($v) && $v instanceof ArrayAccess) return $v;
	if (is_string($v)) return WebSignatureFromString($v);
	return null;
}

function WebCompiledSignatureFromPartial(array $a) {
	if (!isset($a[0]))
		return $a;
	else {
		$x = array_merge(WebSignatureFromString($a[0]), $a);
		unset($x[0]);
		return $x;
	}
}

function WebURLMatchesPattern($url, $pattern, &$vars) {
	$url = explode('/', trim($url, '/'));
	$patternHasWildcard = (strpos($pattern, '*') !== false);
	$pattern = explode('/', trim($pattern, '/'));
	$matches = array();
	
	if (!$patternHasWildcard && sizeof($url) > sizeof($pattern))
		return false;
	
	$i = 0; foreach ($pattern as $part) {
		$matchingPart = @$url[$i];
		
		if (strlen($part) > 1 && $part[0] == '$') {
			if ($part[1] != '*') {
				$varName = substr($part, 1);
				$matches[$varName] = $matchingPart;
			} else {
				$varName = substr($part, 1);
				$urlPart = $url; array_splice($urlPart, 0, $i);
				$matches[$varName] = $urlPart;
				break;
			}
		} else if ($part != $matchingPart)
			return false;
			
		$i++;
	}
	
	$vars = $matches;
	return true;
}

function _WebCleanRequest($x) {
	if (!$x) return null;
	
	if (get_magic_quotes_gpc()) {
		if (is_array($x)) {
			$y = array(); foreach ($x as $k => $v)
				$y[$k] = _WebCleanRequest($v);
			return $y;
		} else
			return str_replace(array("\\'", '\\"', "\\\0", "\\\\"), array("'", '"', "\0", "\\"), $x);
	} else
		return $x;
}

function WebH($x) { return htmlspecialchars((string) $x); }

function WebXMLProlog($encoding) {
	return '<'.'?xml version="1.0" encoding="'.$encoding.'" ?'.'>';
}

function _WebHeaderNameToSERVERKey($name) {
	$name = explode('-', $name);
	$s = 'HTTP';
	foreach ($name as $x)
		$s .= '_' . strtoupper($x);
	return $s;
}

function WebCurrentGlobalRequest() {
	if (PHP_SAPI == 'cli') // command line
		return WebCLIRequest::instance();
	else
		return WebGlobalRequest::instance();
}

function WebRunGlobalResponder($class) {
	$x = new $class();
	$resp = $x->responseForRequest(WebCurrentGlobalRequest());
	if (!$resp)
		$resp = new WebErrorResponse("500 Internal Server Error");
	$resp->render();
}

function WebRun(/* $responder, ... */) {
	$a = func_get_args(); if (is_array($a[0])) $a = $a[0];
	$req = WebCurrentGlobalRequest();
	foreach ($a as $responderClass) {
		$shouldUse = call_user_func(array($responderClass, 'shouldBeUsedForRequest'), $req);
		if ($shouldUse) {
			CLog($responderClass, __FUNCTION__ . ' will use responder class');
			
			$x = new $responderClass();
			$result = $x->responseForRequest($req);
			if ($result) $result->render();
			return $result;
		}
	}
}

?>